//C-DRG 上传结果查询
import React from 'react';
import { Card, Row, Col, Form, DatePicker, Select, Button, Tooltip, message, Pagination ,Input,Icon,Popconfirm} from 'antd';
import { $http } from 'containers/config/https';
import PubilcTablePagination from '../common/PubilcTablePagination.jsx'; // 公共table组件
import Moment from 'moment';
import { Util, dayFormat } from 'tools/index';
import RangeDatePicker from 'components/rangePicker/index';
import store from 'store';
import './style/index.less';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';

let userData ;

const { Option } = Select;
const FormItem = Form.Item;
const formItemLayout = {    // label 和input宽度
    labelCol: { span: 5 },
    wrapperCol: { span: 19 },
};
const inputLayout={
    labelCol:{span:7},wrapperCol:{span:17}
}

const QueryCDRGResult=Form.create()(
  class extends React.Component {
    constructor(props) {
        super(props);
        var date = new Date()
        this.state = {
            hospID: '',
            tableData: [], 
            pageSize: 20,
            page: 1,
            columns: [],
            total: 0,
            tableWidth: 0,
            locData: [],
            locType: "CL",
            conStatusAry: [],
            tableType: 'C',
            locID: '',
            conApplyLocID: '',
            conStatusCode: '',
            sortColumn:'admDischagDate',
            patMedicalNo:'',
            patName:'', //病人姓名
            startDisDate:Moment().subtract(6,'days').format('YYYY-MM-DD'),
            endDisDate:Moment().subtract(4,'days').format('YYYY-MM-DD'),
            uploadResultCode:undefined,
            inDrgResultCode:undefined,
            uploadStatus:[],            //上传状态数据集
            inGroupStatus:[],           //入组结果数据集
            updStDate:undefined,        //上传开始默认日期
            updSpDate:undefined,        //上传截至默认日期
        }
        userData = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
    }
    componentDidMount() {
        this.initDefaultValue();
        this.GetPageDataSource();
    }
    //查询默认数据
    initDefaultValue = () => {
        let date = new Date()
        let data = {
            params: [{
                defaultAppObj: {
                    DRGsRequestRecord: ["DRGUploadSortCell","DRGInGroupDefStatus","DRGUploadDefStatus","DRGSDisSTDate","DRGSDisENDDate","DRGSRecLocType","DRGSUpdStDefDate","DRGSUpdSpDefDate"],
                }
            }]
        }
        $http.post('urlS', this, {
            code: "04110023",
            data: data,
            success: (res) => {
                if (+res.errorCode === 0) {
                    const regex = /@/g;
                    this.setState({
                        defaultValueObj: res.result,
                        startDisDate: res.result.DRGSDisSTDate ? res.result.DRGSDisSTDate : this.state.startDisDate,
                        endDisDate: res.result.DRGSDisENDDate ? res.result.DRGSDisENDDate : this.state.endDisDate,
                        locType:res.result.DRGSRecLocType?(res.result.DRGSRecLocType.replace(regex, '^')):this.state.locType,
                        updStDate:(res.result.DRGSUpdStDefDate)?(res.result.updStDefDate.replace(regex, '^')):this.state.updStDate,
                        updSpDate:(res.result.DRGSUpdStDefDate)?(res.result.updSpDefDate.replace(regex, '^')):this.state.updSpDate,
                        uploadResultCode:(res.result.DRGUploadDefStatus)?(res.result.DRGUploadDefStatus.replace(regex, '^')):this.state.uploadResultCode,
                        inDrgResultCode:(res.result.DRGInGroupDefStatus)?(res.result.DRGInGroupDefStatus.replace(regex, '^')):this.state.inDrgResultCode,
                        sortColumn:(res.result.DRGUploadSortCell)?(res.result.DRGUploadSortCell.replace(regex, '^')):this.state.sortColumn,
                    },()=>{
                        this.loadColumn();
                        this.handleQuery();
                        this.getLocData();
                    })
                }
            }
        })
    }

    /**查询页面数据集 */
    GetPageDataSource = () => {
        let data={params:[{}]}
        $http.post('urlS', this, {
            code: "05900003",
            data: data,
            success: (res) => {
                if (+res.errorCode === 0) {
                    this.setState({
                        uploadStatus:res.result.uploadStatus?res.result.uploadStatus:undefined,
                        inGroupStatus:res.result.inGroupStatus?res.result.inGroupStatus:undefined
                    })
                }
            }
        })
    }

    //查询列头数据
    loadColumn = () => {
        let data = {
            params: [{
                compontName: "QueryCDRGResult",
				// type: "C",
				reactCode: ['QueryCDRGResult']
            }]
        }
        $http.post('urlDeault', this, {
            code: "01040073",
            data: data,
            success: (res) => {
                if (+res.errorCode === 0) {
                    var totalWidth = 0;
                    let resData = res.result.C;
                    for (let index = 0; index < resData.length; index++) {
                        // widthNumber += parseInt(res.result[index].width);
                        // resData[index].width=resData[index].width+'px'
                        let columnCode = resData[index].code;
                        if ((columnCode == 'uploadResult') || (columnCode == 'inDRGIDDesc') || (columnCode == 'conAims') || (columnCode == 'conItemIdea')) {
                            resData[index].onCell = () => {
                                return {
                                    style: {
                                        maxWidth: 200,
                                        overflow: 'hidden',
                                        whiteSpace: 'nowrap',
                                        textOverflow: 'ellipsis',
                                        cursor: 'pointer'
                                    }
                                }
                            }
                            resData[index].render = (text) => <Tooltip placement="topLeft" title={text}>{text}</Tooltip>
                        }

                    }
                    let arr = resData && resData.map((item, index) => {
						return {
							...item,
							key: index,
							widthNum: parseInt(item.width),
							title: <div onDoubleClick={() => this.mainColumnRef.onOpenModel()}>{userData.language == 'EN' ? (item && item.enDescripts ? item.enDescripts : item.title) : item.title}</div>,
						}
					});
					let filterArr = arr.filter(function (item) { return item.display === 'Y' });
                    let butData = res.result.B;
                    const optionObj = {
                        title: userData.language == 'EN' ? 'Operation' : '操作',
                        key: filterArr.length,
                        // fixed: 'right',
                        align: 'center',
                        width: '250px',
						widthNum: 250,
                        render: (text, record) => {
                            return (
                                ((!Util.isEmpty(record)) && (butData.length>0)) ? (
                                    <span>                                       
                                       {butData.map((item,index)=>{
                                           if ((item.display === "Y")&&(record[item.code]==="Y")){
                                            return (<Button key={index} type="primary" size="small"
                                                className={(index===0)?'firstBtn':((index===1)?'secondBtn':((index===2)?'thirdBtn':'fourBtn'))}
                                                onClick={()=>{this.operationClick(record,item)}}
                                                >
                                                {item.descripts}
                                                </Button>)
                                            }
                                        })}   
                                    </span>
                                ) : null
                            )
                        }
                    }
                    filterArr.push(optionObj);
					for (var i = 0; i < filterArr.length; i++) {
						totalWidth += filterArr[i].widthNum;
					}
                    this.setState({
                        columns: filterArr,
                        tableWidth:totalWidth+ "px",
                    })
                }
            }
        })
    }

    // 获取科室信息
    getLocData = () => {
        let data = {
            "params": [{
                hospID: this.state.hospID ? this.state.hospID : userData.hospID,          // 会诊医院id
                type: this.state.locType
            }]
        };
        $http.post('urlDeault', this, {
            code: "04020008",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    this.setState({
                        locData: res.result.Data
                    })
                }
            },
            error: function (error) {
                message.error('失败：' + error);
            }
        });
    }

    /**
     * 行上操作按钮点击事件
     * @param {行记录数据} record 
     */
    operationClick =(record,btnItem)=>{
        let btnCode=btnItem.code
        if (Util.isEmpty(btnCode)){return}
        let data = {
            "params": [{
                recordID: [record.ID],          // 记录id
                type: btnCode,
                admID:[record.admID]
            }]
        };
        $http.post('urlDeault', this, {
            code: "05900001",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    message.success(res.result.message)
                    this.handleQuery();
                    // this.setState({
                    //     locData: res.result.Data
                    // })
                }
            },
            error: function (error) {
                message.error('失败：' + error);
            }
        });
    }

    

    handleQuery = () => {
        const formData = this.props.form.getFieldsValue();
        let data = {
            params: [{
                hospID: userData.hospID,
                startDisDate:this.state.startDisDate?Moment(this.state.startDisDate).utcOffset(480).format('YYYY-MM-DD') : '',
                endDisDate:this.state.endDisDate?Moment(this.state.endDisDate).utcOffset(480).format('YYYY-MM-DD') : '',
                startDate: this.state.updStDate ? Moment(this.state.updStDate).utcOffset(480).format('YYYY-MM-DD') : '',
                endDate: this.state.updSpDate ? Moment(this.state.updSpDate).utcOffset(480).format('YYYY-MM-DD') : '',
                uploadResultCode:this.state.uploadResultCode?this.state.uploadResultCode:'',
                inDrgResultCode:this.state.inDrgResultCode?this.state.inDrgResultCode:'',
                outHospLocID: this.state.conApplyLocID,
                patMedicalNo: formData.patMedicalNo,
                patName: (formData.patName).trim(),
            }],
            pagination: [{
                pageSize: this.state.pageSize,
                currentPage: this.state.page,
                sortColumn: this.state.sortColumn,
                sortOrder: 'desc'
            }]
        };
        $http.post('urlS', this, {
            code: '05900002',
            data: data,
            success: (res) => {
                console.dir(res);
                if (res.errorCode === "0") {
                    for (let index = 0; index < res.result.Data.length; index++) {
                        res.result.Data[index].key = index + 1;
                    }
                    this.setState({
                        total: res.result.TotalCount,
                        tableData: res.result.Data,
                    });
                } else {
                    this.setState({
                        total: 0,
                        tableData: []
                    });
                }
            }
        });
        this.commonChild.handleLoading();
    }

    // 提供修改page和pageSize的回调函数
    compilePage(page, pageSize) {
        // 修改page，或者pageSize
        this.setState({ page: page, pageSize: pageSize }, () => {
            // 重新调用查询方法
            this.handleQuery();
        })
    }

    // 调用公共组件的连接事件
    onRef = (ref) => {
        this.child = ref
    }
    handleOnRef = (ref) => {
        this.commonChild = ref
    }
    // 会诊状态
    handleConStatus = (code) => {
        this.setState({
            conStatusCode: code
        }, () => {
            this.handleQuery();
        })

    }
    uploadResultChange= (code) => {
        // console.log("code",code)
        this.setState({ uploadResultCode: code,page: 1, pageSize: 20, },
            () => { this.handleQuery() });
    }

    inDrgResultChange= (code) => {
        // console.log("code",code)
        this.setState({ inDrgResultCode: code,page: 1, pageSize: 20, },
            () => { this.handleQuery() });
    }

    handleConApplyLocID = (id) => {
        this.setState({ conApplyLocID: id,page: 1, pageSize: 20, },
            () => { this.handleQuery() });
    }

    handleLocID = (id) => {
        this.setState({ handleLocID: id },
            () => { this.handleQuery() });
    }

    startDisDateChange(date) {
        console.log("data1"+ date)
        this.setState({
            startDisDate: date,
            page: 1, pageSize: 20,
        })
    }

    endDisDateChange(date) {
        console.log("data2"+ date)
        this.setState({
            endDisDate: date,
            page: 1, pageSize: 20,
        })
    }

    startChange(e) {
        this.setState({
            updStDate: e ? Moment(e).format(dayFormat) : '',
            page: 1, pageSize: 20,
        })
    }

    endChange(e) {
        this.setState({
            updSpDate: e ? Moment(e).format(dayFormat) : '',
            page: 1, pageSize: 20,
        })
    }
    // 回车查询登记号
    patNodownE = (e, type) => {
        if (e.keyCode === 13) {
            this.searchUser(type)
        }
    }

    searchUser = (type) => {
        var data;
        let { cardType, cardNo, patNo, cardTypeData } = this.state
        if (type === 'patMedicalNo') {
            this.setState({page: 1, pageSize: 20,},()=>{this.handleQuery();})            
        }
        if (type === 'patName') {
            this.setState({page: 1, pageSize: 20,},()=>{this.handleQuery()})
        }
    };

    // 查询条件 --- 登记号
    patMedicalNo = (e) => {
        this.setState({ patMedicalNo: e.target.value,page: 1, pageSize: 20, });
    };
    // 查询条件 --- 病人姓名
    patName = (e) => {
        let patientName= e.target.value;
        let patName = patientName.trim();
        this.setState({ patName:patName,page: 1, pageSize: 20, });
    };


	onMainColumnRef = ref => {
		this.mainColumnRef = ref;
	}

    render() {
        var date = new Date()
        let {startDisDate,endDisDate,uploadStatus,inGroupStatus,updStDate,updSpDate,uploadResultCode,inDrgResultCode}=this.state
        // 组件所需参数
        const param = {
            // 表头配置
            columns: this.state.columns,
            // 表格数据
            data: this.state.tableData,
            // 数据总条数
            total: this.state.total,
            // 数据页数
            page: this.state.page,
            // 表格的宽度
            x: this.state.tableWidth,
            pageSize:this.state.pageSize,
        }
        //上传状态
        let uploadStatusOption=[]
        uploadStatus && uploadStatus.map((item,index)=>{
            uploadStatusOption.push(
                <Option key={index} code={item.code} value={item.value} title={item.descripts}>
                {item.descripts}</Option>
            )
        })
        //入组结果
        let inGroupStatusOption=[]
        inGroupStatus && inGroupStatus.map((item,index)=>{
            inGroupStatusOption.push(
            <Option key={index} code={item.code} value={item.value} title={item.descripts}>
            {item.descripts}</Option>)
        })
        console.log("startDisDate:"+startDisDate)
        console.log("endDisDate:"+endDisDate)
        const { getFieldDecorator } = this.props.form;
        return (
            <div className="WarehouseEntryCheck1">
                <div>
                    <Row>
                        <Card
                            size="small"
                            title="出院病人病案首页上传信息结果查询"
                            headStyle={{ background: 'rgb(66, 185, 131)' }}
                        >
                            <Form>
                                <Col span={22}>
                                        <Row>
                                            <Col span={7}>
                                                <FormItem {...formItemLayout} label="出院时间">
                                                    <RangeDatePicker  format='YYYY-MM-DD' style={{ }}
                                                        isChange={true}
                                                        startDate={startDisDate} endDate={endDisDate}
                                                        startChange={this.startDisDateChange.bind(this)}
                                                        endChange={this.endDisDateChange.bind(this)} />
                                                </FormItem>
                                            </Col>
                                            <Col span={7}>
                                                <FormItem {...formItemLayout} label="上传时间">
                                                    <RangeDatePicker  format='YYYY-MM-DD' style={{ textAlign: "center" }}
                                                        isChange={true}
                                                        allowClear
                                                        startDate={updStDate}
                                                        endDate={updSpDate}
                                                        startChange={this.startChange.bind(this)} endChange={this.endChange.bind(this)} />
                                                </FormItem>
                                            </Col>
                                            <Col span={5}>
                                                <FormItem {...inputLayout} label="上传结果">
                                                    {getFieldDecorator('uploadResult', {
                                                        initialValue: uploadResultCode,
                                                        rules: [{ required: false, message: '上传结果' }]
                                                    })(
                                                        <Select
                                                            allowClear
                                                            style={{textAlign: "center" }}
                                                            showSearch
                                                            onChange={this.uploadResultChange}
                                                            optionFilterProp='role'
                                                        >
                                                        {uploadStatusOption}
                                                        </Select>
                                                    )}
                                                </FormItem>
                                            </Col>
                                            <Col span={5}>
                                                <FormItem {...inputLayout} label="入组结果">
                                                    {getFieldDecorator('inDrgResult', {
                                                        initialValue: inDrgResultCode,
                                                        rules: [{ required: false, message: '入组结果' }]
                                                    })(
                                                        <Select
                                                            allowClear
                                                            style={{textAlign: "center" }}
                                                            showSearch
                                                            onChange={this.inDrgResultChange}
                                                            optionFilterProp='role'
                                                        >
                                                            {inGroupStatusOption}
                                                        </Select>
                                                    )}
                                                </FormItem>
                                            </Col>
                                        </Row>
                                        <Row>
                                            <Col span={5}>
                                                <FormItem {...formItemLayout} style={{marginLeft:'30px'}} label="出院科室">
                                                    {getFieldDecorator('conApplyLocID', {
                                                        initialValue: undefined,
                                                        rules: [{ required: false, message: '出院科室' }]
                                                    })(
                                                        <Select
                                                            allowClear
                                                            style={{textAlign: "center", width: '260px' }}
                                                            showSearch
                                                            onChange={this.handleConApplyLocID}
                                                            optionFilterProp='role'
                                                        >
                                                            {this.state.locData.map(data => (
                                                                    <Select.Option
                                                                        role={data.code + '^' + data.descripts + '^' + data.descriptsSPCode}
                                                                        key={data.id}
                                                                    >{data.descripts}
                                                                    </Select.Option>
                                                                )
                                                            )}
                                                        </Select>
                                                    )}
                                                </FormItem>
                                            </Col>
                                            <Col span={5}>
                                                <FormItem {...formItemLayout} label="病案号">
                                                    {getFieldDecorator('patMedicalNo',{
                                                        initialValue:'',
                                                    })(
                                                        <Input allowClear
                                                            style={{ width: '260px' }}
                                                            placeholder="输入病案号回车查询"
                                                            className='input'
                                                            onChange={(event) => { this.patMedicalNo(event) }}
                                                            onKeyUp={(e) => { this.patNodownE(e, 'patMedicalNo'); }} />

                                                    )}
                                                </FormItem>
                                            </Col>
                                            <Col span={5}>
                                                <FormItem {...formItemLayout} label="病人姓名">
                                                    {getFieldDecorator('patName',{
                                                        initialValue:'',
                                                    })(
                                                        <Input allowClear
                                                            style={{ width: '260px' }}
                                                            placeholder="输入病人姓名回车查询"
                                                            className='input'
                                                            onChange={(event) => { this.patMedicalNo(event) }}
                                                            onKeyUp={(e) => { this.patNodownE(e, 'patName'); }} />
                                                    )}
                                                </FormItem>
                                            </Col>
                                        </Row>
                                </Col>
                            </Form>
                            <Col span={2} style={{ marginTop: '4px' }}>
                                <Row style={{ marginBottom: '18px' }} className="button">
                                    &nbsp;&nbsp;&nbsp;&nbsp;<Button type="primary" style={{marginLeft: '36px'}}
                                        onClick={this.handleQuery}
                                    >查询</Button>
                                </Row>
                            </Col>

                        </Card>
                    </Row>
                </div>
                <div>
                    {/* handelThis将夫组件的属性与方法给子组件访问 */}
                    <PubilcTablePagination param={param} handelThis={this} onRef={this.handleOnRef} />
                    <ColumnAuthoritysModel
                        clientWidth='800px'
                        compontName='QueryCDRGResult'
                        configType="C"
                        onRef={this.onMainColumnRef}
                        reloadData={this.loadColumn}
                    />
                </div>
            </div>
        )
    }

}
);
export default QueryCDRGResult;